<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import type { Ref } from 'vue'
import {
  CircleCheck,
  Delete,
  Edit,
  User,
  DArrowRight,
  Search,
  Refresh,
  Plus,
  Download
} from '@element-plus/icons-vue'
import type { UploadProps, UploadFile, FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

import { parseTime, baseURL } from '@/utils/validate'
// 引入组件
import Pagination from '@/components/Pagination/Index.vue'

import {
  classifyAdd,
  classifyDelete,
  classifyEdit,
  getClassifyList
} from '@/api/admin/product/classify'
import { upload } from '@/api/common'
import { compress } from '@/utils/validate'
// queryForm ref
const queryFormRef = ref<FormInstance>()
/**form ref */
const formRef = ref<FormInstance>()

/**查询条件 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  title: '',
  status: ''
})
const sys_normal_disable = ref([
  { label: '正常', value: '0' },
  { label: '停用', value: '1' }
])
/**表格的loading */
const loading = ref(false)
/**表格数据 */
const dataList: any = ref([])
/**总共条数 */
const total = ref(0)

// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 表单参数
const form = ref({
  classifyId: undefined,
  title: undefined,
  cover: undefined,
  remark: undefined,
  status: '0'
})
// 表单校验
const rules = ref({
  title: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  cover: [{ required: true, message: '封面不能为空', trigger: 'change' }]
})

const handleChange: UploadProps['onChange'] = async (uploadFile: any, uploadFiles: any) => {
  // imgUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log('uploadFile, uploadFiles', uploadFile, uploadFiles)
  const { compressFile, compressBase64 }: any = await compress(uploadFile.raw, 50)
  console.log('compressFile, compressBase64', compressFile, compressBase64)
  upload({ name: 'cover', base64: compressBase64 }).then((response: any) => {
    console.log('response', response.filePath)
    form.value.cover = response.filePath
    //图片上传成功,清除掉对应图片校验结果
    nextTick(() => {
      formRef.value?.clearValidate('cover')
    })
  })
}
//
const beforeUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('单张图片大小不能超过10MB!')
    return false
  }
  return true
}
// 查询产品分类列表
const getList = () => {
  loading.value = true
  getClassifyList(queryParams.value)
    .then((response: any) => {
      dataList.value = response.rows
      total.value = response.total
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
/**重置数据 */
const resetQuery = () => {
  nextTick(() => {
    // 重置表单
    if (queryFormRef.value) {
      queryFormRef.value?.resetFields()
    }
    handleQuery()
  })
}

/**
 * 非单个禁用
 */
const single = ref(true)
/**
 * 选中多个进行删除
 */
const multiple = ref(true)
/**选中删除的id */
const ids = ref([])

/**
 * 删除
 */
const handleDelete = (row: any) => {
  const classifyIds = row.classifyId || ids.value
  ElMessageBox.confirm('是否确认删除产品分类编号为"' + classifyIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      return classifyDelete(classifyIds)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

const handleExport = () => {}

/**
 * 分类状态修改
 */
const handleStatusChange = (row: any) => {
  const text = row.status === '0' ? '启用' : '停用'
  ElMessageBox.confirm('确认要"' + text + '""' + row.title + '"产品分类吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      const params = {
        classifyId: row.classifyId,
        status: row.status
      }
      return classifyEdit(params)
    })
    .then(() => {
      getList()
      ElMessage.success(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}

/**
 * 选择条数
 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item?.classifyId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 新增
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加产品分类'
}

/**
 * 修改
 */
const handleUpdate = (row: any) => {
  console.log('修改===', row)
  open.value = true
  title.value = '修改产品分类'
  form.value = {
    // ...row
    classifyId: row.classifyId,
    title: row.title,
    cover: row.cover,
    remark: row.remark,
    status: row.status
  }
}
// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}
// 表单重置
const reset = () => {
  form.value = {
    classifyId: undefined,
    title: undefined,
    cover: undefined,
    remark: undefined,
    status: '0'
  }

  if (formRef.value) {
    formRef?.value?.resetFields()
  }
}
/** 提交按钮 */
const submitForm = () => {
  formRef?.value?.validate((valid: any) => {
    console.log('===', !form.value.classifyId)
    if (valid) {
      if (!form.value.classifyId) {
        classifyAdd(form.value).then((response: any) => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      } else {
        classifyEdit(form.value).then((response: any) => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
const sys_notice_status = ref([
  { label: '正常', value: '0', elTagType: 'primary' },
  { label: '关闭', value: '1', elTagType: 'danger' }
])
// 初始化列表数据
getList()
</script>

<template>
  <div class="classify">
    <!-- 条件查询 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="分类名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入分类名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="分类状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮组 -->
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="1.5">
        <el-button type="primary" plain :icon="Plus" @click="handleAdd">新增 </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :icon="Delete" :disabled="multiple" @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain :icon="Download" @click="handleExport"> 导出</el-button>
      </el-col>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        key="title"
        label="分类名称"
        align="center"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column key="cover" label="分类封面" width="120" align="center">
        <template #default="{ row }">
          <el-image
            style="width: 80px; height: 80px"
            :src="baseURL() + row.cover"
            fit="cover"
            :preview-src-list="[baseURL() + row.cover]"
            :preview-teleported="true"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column key="status" label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        key="createBy"
        label="创建人"
        align="center"
        prop="createBy"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, null) }}</span>
        </template>
      </el-table-column>
      <el-table-column key="remark" label="备注" align="center" prop="remark" width="120" />
      <el-table-column
        label="操作"
        align="center"
        width="250"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)">
            <el-icon> <edit /> </el-icon>修改
          </el-button>
          <el-button type="primary" link @click="handleDelete(scope.row)">
            <el-icon> <delete /> </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :total="total"
      @pagination="getList"
    />
    <!-- 添加或修改产品分类对话框 -->
    <el-dialog v-model="open" :title="title" width="780px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入产品分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类封面" prop="cover">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                action="#"
                :auto-upload="false"
                :on-change="handleChange"
                :before-upload="beforeUpload"
              >
                <img v-if="form.cover" :src="baseURL() + form.cover" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_notice_status"
                  :key="dict.value"
                  :label="dict.value"
                  border
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <!-- todo 这个地方可以换成富文本框 -->
              <el-input v-model="form.remark" :rows="2" type="textarea" placeholder="请输入备注" />
              <!-- <editor v-model="form.noticeContent" :min-height="192" /> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>
<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
